import sys
from PyQt5 import QtWidgets, QtGui
import subprocess
import os

from views.settings import SettingsWidget
from views.review import ReviewWidget
from views.shared import Label
from models.review import Review


class HomeWindow(QtWidgets.QWidget):
    def __init__(self, games, reviews):
        super(HomeWindow, self).__init__()

        # Basic Window Properties
        self.setWindowTitle('Icicle Game Launcher')
        self.resize(500, 500)

        # Window Components
        self.createMenu()
        self.games = games
        self.reviews = reviews
        self.gameList = GameListWidget(self.games, self)
        self.mainButton = DynamicButton(self)
        self.infoLabel = Label('Game Information')
        self.gameInfo = GameInfoWidget()
        self.ratingLabel = Label('Rating and Comments')
        self.ratingCombo = RatingCombo()
        self.gameComments = CommentsWidget()
        self.feedbackSubmit = SubmitButton(self)

        # Main Window Layout
        self.mainLayout = QtWidgets.QHBoxLayout()
        self.mainLayout.addWidget(self.gameList)

        # Right Section Layout
        self.rightLayout = QtWidgets.QVBoxLayout()
        self.rightLayout.addWidget(self.mainButton)
        self.rightLayout.addWidget(self.infoLabel)
        self.rightLayout.addWidget(self.gameInfo)
        self.rightLayout.addWidget(self.ratingLabel)
        self.rightLayout.addWidget(self.ratingCombo)
        self.rightLayout.addWidget(self.gameComments)
        self.rightLayout.addWidget(self.feedbackSubmit)

        self.mainLayout.addLayout(self.rightLayout)

        # Initialize the layout
        self.mainWindow = QtWidgets.QWidget()
        self.mainWindow.setLayout(self.mainLayout)

        # Set up support for pages
        self.layout = QtWidgets.QStackedLayout()
        self.layout.setMenuBar(self.menuBar)
        # Make sure we know which index corresponds to which window
        self.layout.insertWidget(0, self.mainWindow)
        self.layout.insertWidget(1, SettingsWidget())

        self.setLayout(self.layout)
        # Start on the main window
        self.layout.setCurrentIndex(0)

        self.reviewWidgets = []

        # Render the window
        self.show()

    def createMenu(self):
        self.menuBar = QtWidgets.QMenuBar()

        self.fileMenu = QtWidgets.QMenu("&File", self)

        self.gamesAction = self.fileMenu.addAction("&Games")
        self.gamesAction.triggered.connect(self._games)

        self.settingsAction = self.fileMenu.addAction("&Settings")
        self.settingsAction.triggered.connect(self._settings)

        self.exitAction = self.fileMenu.addAction("E&xit")
        self.exitAction.triggered.connect(self.close)

        self.menuBar.addMenu(self.fileMenu)

    def showGame(self, game):
        # Check if a game is playable, determine function
        # of button based on that
        self.mainButton.playable()

        # Populate the info pane with the game's info
        self.gameInfo.changeGameInfo(game.getTitle(), True, False)
        self.gameInfo.changeGameInfo(game.getAuthor(), False, True)
        self.gameInfo.changeGameInfo(game.getDescription(), False, True)

        self.gameComments.reset()
        self.ratingCombo.reset()

        self.loadReviews(game)

    def loadReviews(self, game):
        reviews = [review for review in self.reviews
                   if review.getGameId() == game.getId()]
        for reviewWidget in self.reviewWidgets:
            reviewWidget.setParent(None)
        self.reviewWidgets.clear()
        for review in reviews:
            self.addReview(review)

    def addReview(self, review):
        reviewWidget = ReviewWidget(review)
        self.rightLayout.addWidget(reviewWidget)
        self.reviewWidgets.append(reviewWidget)

    def _games(self):
        self.layout.setCurrentIndex(0)

    def _settings(self):
        self.layout.setCurrentIndex(1)


# The following are the classes for the various GUI widgets
class GameListWidget(QtWidgets.QListWidget):
    def __init__(self, games, parentWidget):
        super(GameListWidget, self).__init__()
        self.games = games
        self.gameDict = {}
        for game in games:
            gameWidget = QtWidgets.QListWidgetItem(game.getTitle())
            self.addItem(gameWidget)
            self.gameDict[game.getTitle()] = game
        self.parentWidget = parentWidget
        self.clicked.connect(self.gameClicked)
        self.itemDoubleClicked.connect(self.tryLaunch)

    def gameClicked(self, gameWidget):
        game = self.gameDict[gameWidget.data(0)]
        self.parentWidget.showGame(game)

        if game.getStatus() == 'ready':
            self.parentWidget.mainButton.playable()
        elif game.getStatus() == 'install':
            self.parentWidget.mainButton.notInstalled()
        elif game.getStatus() == 'update':
            self.parentWidget.mainButton.needUpdate()

    def tryLaunch(self, gameWidget):
        game = self.gameDict[gameWidget.data(0)]
        game.launch()
        self.parentWidget.mainButton.playable()


class DynamicButton(QtWidgets.QPushButton):
    def __init__(self, parentWidget):
        super(DynamicButton, self).__init__()
        self.parentWidget = parentWidget
        self.clicked.connect(self.btnClicked)

    def playable(self):
        self.setText("Play")

    def notInstalled(self):
        self.setText("Install")

    def needUpdate(self):
        self.setText("Update")

    def btnClicked(self):
        selected = self.parentWidget.gameList.selectedItems()
        game = self.parentWidget.gameList.gameDict[selected[0].data(0)]
        game.launch()
        self.parentWidget.mainButton.playable()


class GameInfoWidget(QtWidgets.QTextEdit):
    def __init__(self):
        super(GameInfoWidget, self).__init__()
        self.setReadOnly(True)

    def changeGameInfo(self, newText, clear, newLine):
        if clear:
            self.clear()
        if newLine:
            self.insertPlainText('\n')
        self.insertPlainText(newText)


class RatingCombo(QtWidgets.QComboBox):
    def __init__(self):
        super(RatingCombo, self).__init__()
        self.addItem('0')
        self.addItem('1')
        self.addItem('2')
        self.addItem('3')
        self.addItem('4')
        self.addItem('5')

    def reset(self):
        self.setCurrentIndex(0)


class CommentsWidget(QtWidgets.QTextEdit):
    def __init__(self):
        super(CommentsWidget, self).__init__()

    def reset(self):
        self.clear()


class SubmitButton(QtWidgets.QPushButton):
    def __init__(self, parentWidget):
        super(SubmitButton, self).__init__()
        self.setText('Submit')
        self.clicked.connect(self.submit)
        self.parentWidget = parentWidget

    def submit(self):
        selected = self.parentWidget.gameList.selectedItems()
        game = self.parentWidget.gameList.gameDict[selected[0].data(0)]
        review = Review()
        review.setAuthor("Anonymous")
        review.setBody(self.parentWidget.gameComments.toPlainText())
        review.setRating(int(self.parentWidget.ratingCombo.currentText()))
        review.setGameId(game.getId())
        Review.submitRemote(review, game)
        self.parentWidget.addReview(review)
        self.parentWidget.ratingCombo.reset()
        self.parentWidget.gameComments.reset()